from django.shortcuts import render, redirect, reverse, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib import auth
from apps.crm import forms
from apps.crm.models import User
from django.core.mail import send_mail
# Create your views here.

def base(request, template_name):
    return render(request, template_name)

@login_required
def index(request):
    return render(request, 'crm/index.html')

def logout(request):
    # 执行退出
    auth.logout(request)
    return redirect(reverse('login'))

def login(request):
    if request.method == 'GET':
        form = forms.LoginForm()
        return render(request, 'crm/login.html', {'form': form})
    else:
        form = forms.LoginForm(request.POST)
        if form.is_valid():
            print('data ok')
            email = request.POST.get('email','')
            password = request.POST.get('password','')
            user = auth.authenticate(email=email, password=password)
            if user is not None:
                auth.login(request, user)
                return redirect(reverse('index'))
            else:
                print("data error")
                return render(request, 'crm/login.html', {'form': form, 'error': "用户名或密码错误！"})
        else:
            print("error")
            return render(request, 'crm/login.html', {'form': form, 'error': form.errors})

def job_count(request):
    # return render(request, 'crm/test.html')
    return render(request, 'job/job_count.html')

def register(request):
    if request.method == 'GET':
        form = forms.RegisterForm()
        return render(request, 'crm/register.html', {'form': form})
    else:
        form = forms.RegisterForm(request.POST)
        if form.is_valid():
            print('data ok')
            email = request.POST.get('email', '')
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            password2 = request.POST.get('password2', '')
            if password == password2:
                print(email, username, password)
                User.objects.create_user(email=email, username=username, password=password)
                send_mail('主题send_mail', '内容<br/>.内容', '752151766@qq.com',
                          ['{}'.format(email)], fail_silently=False)
                return render(request, 'crm/login.html', {'form': form})
            else:
                print("两次密码不一致")
                return render(request, 'crm/register.html', {'form': form, 'error': '两次密码不一致'})

def test_session(request):
    request.session['myname'] = 'caoyong'
    return HttpResponse(request.session)

def test_celery(request):
    # 导入任务
    from apps.count.tasks import checking_in_statistics
    # # 调用任务
    result = checking_in_statistics.delay()
    # # print(dir(result))
    # # print(type(result))
    # # 需求： 用户提任务，指定间隔（N Seconds）
    # from djcelery.models import PeriodicTask, IntervalSchedule, CrontabSchedule
    # cron_n = 11
    # cron_type = 'seconds'
    # # 新创建， （对象， True）
    # # 已存在， （对象， False）
    # interval = IntervalSchedule.objects.get_or_create(every=cron_n, period=cron_type)[0]
    # print(interval)
    # task = PeriodicTask.objects.get_or_create(name='add100')[0]
    # task.interval = interval
    # task.args = [1, 1]
    # task.task = 'apps.crm.tasks.add'
    # task.save()


    return HttpResponse('ok')

from django.db import transaction

@transaction.atomic()
def test_transaction(request):
    import datetime
    import time
    from apps.crm.models import CheckingIn
    # 准备工作
    sid = transaction.savepoint()
    # now0 = datetime.datetime.now()
    # today0 = datetime.date.today()
    # time0 = now0.strftime("%X")
    # CheckingIn.objects.create(date=today0, sign_time=time0, user=request.user)
    #
    # sid1 = transaction.savepoint()
    # # raise KeyError
    # try:
    #     CheckingIn.objects.create(date=today0, sign_time=time0, user=request.user)
    #     raise KeyError
    #     transaction.savepoint_commit(sid1)
    # except Exception as ex:
    #     transaction.savepoint_rollback(sid)
    # # print('get_rollback:', transaction.get_rollback())

    with transaction.atomic():
        # 准备工作
        now0 = datetime.datetime.now()
        today0 = datetime.date.today()
        time0 = now0.strftime("%X")
        CheckingIn.objects.create(date=today0, sign_time=time0, user=request.user)
        # 设置回滚标志
        transaction.set_rollback(True)
    # if transaction.get_rollback():
    #     # 回滚
    #     transaction.savepoint_rollback(sid)
    # else:
    #     # 提交
    #     transaction.savepoint_commit(sid)

    return HttpResponse('test_transaction')


#single
# from django.core.mail import send_mail
# send_mail('主题send_mail', '内容<br/>.内容', '752151766@qq.com',
#           ['752151766@qq.com'], fail_silently=False)

# # some
# from django.core.mail import send_mass_mail
# message1 = ('主题send_mass_mail2', '内容<br/>.内容2', '307324941@qq.com', ['954365910@qq.com', '307324941@qq.com'])
# message2 = ('主题send_mass_mail3', '内容<br/>.内容3', '307324941@qq.com', ['954365910@qq.com'])
# send_mass_mail((message1, message2), fail_silently=False)
# #====
# #EmailMultiAlternatives
# #=====
# from django.core.mail import EmailMultiAlternatives
# subject = '主题EmailMultiAlternatives'
# text_content = '内容<br/>.内容4'
# html_content = '内容<br/>.内容4'
# # 默认text
# msg = EmailMultiAlternatives(subject, text_content,'307324941@qq.com', ['954365910@qq.com', '307324941@qq.com'])
# msg.content_subtype = "html"
# # 附加html类型
# # msg.attach_alternative(html_content, "text/html")
# # 添加附件（可选）
# msg.attach_file('log/all.log')